import { login, getUserProfile, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth.js'
// 暴露子仓库的实例核心的配置项
export default {
  namespaced: true,
  state: {
    // 保存token
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 更新token
    updateToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    // 4.更新用户信息
    updateUserInfo(state, info) {
      state.userInfo = info
    },
    // 清空用户信息
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 发送请求获取token,存储vuex中
    async userLogin(context, loginForm) {
      // context指向仓库的实例
      console.log(context, 'context')
      // 发送获取token
      const res = await login(loginForm)
      console.log('data----vuex', res.data)
      context.commit('updateToken', res.data)
    },
    async getUserInfo(context) {
      try {
        const res = await getUserProfile()
        const info = await getUserDetailById(res.data.userId)
        console.log('res', res)
        context.commit('updateUserInfo', { ...res.data, ...info.data })
      } catch (error) {
        console.log('error', error)
      }
    },
    logout(context) {
      context.commit('removeToken', 'removeUserInfo')
    }
  }
}

